package config

import (
	"github.com/astaxie/beego/config"
	"os"
	"path/filepath"
)

// Config is the main struct for BConfig
type Config struct {
	AppName            string //Application name
	RunMode            string //Running Mode: dev | prod
	ServerName         string
	EnableGzip         bool
	MaxMemory          int64
	EnableErrorsShow   bool
	EnableErrorsRender bool
	Listen             *Listen
	Path               *Path
}

// Listen holds for http and https related config
type Listen struct {
	EnableHTTP    bool
	HTTPPort      string
	EnableHTTPS   bool
	HTTPSPort     string
	HTTPSCertFile string
	HTTPSKeyFile  string
}

type Path struct {
	RootPath string
}

var (
	Ini config.Configer

	Cfg *Config
)

func init() {
	Cfg = new(Config)

	workPath, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	appConfigPath := filepath.Join(workPath, "config.ini")
	cnf, isValid := config.NewConfig("ini", appConfigPath)
	if isValid != nil {
		println("fail to open file : config.ini " + isValid.Error())
		return
	}
	//配置对象
	Ini = cnf

	//获取服务器配置
	listen := new(Listen)
	if Ini.String("http.enable") == "true" {
		listen.EnableHTTP = true
		listen.HTTPPort = Ini.String("http.port")
	}
	if Ini.String("https.enable") == "true" {
		listen.EnableHTTPS = true
		listen.HTTPSPort = Ini.String("https.port")
		listen.HTTPSCertFile = Ini.String("https.certFile")
		listen.HTTPSKeyFile = Ini.String("https.keyFile")
	}

	//设置应用根目录
	var path = new(Path)
	path.RootPath = appConfigPath

	Cfg.Path = path

	//设置服务器启动配置
	Cfg.Listen = listen
}
